"""
项目修改 form
"""

from django import forms
from sa.forms.bootstrap import BootStrapForm
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from sa import models
# 自定义了一个 ColorRadioSelect 插件
from sa.forms.widgets import ColorRadioSelect
from django.utils import timezone


class Edit_ProjectModelForm(BootStrapForm, forms.ModelForm):
    bootstrap_class_exclude = ['color', 'id_big_project', ]

    class Meta:
        model = models.Project
        fields = [
            'sa', 'category', 'software',
            'server_num', 'mfd_num', 'printer_num', 'start_date', 'end_date',
            'status', 'big_project', 'value', 'actors', 'desc'
        ]
        widgets = {
            'start_date': forms.DateInput(attrs={'type': 'date', }),
            'end_date': forms.DateInput(attrs={'type': 'date', }),
            # 'end_date': forms.DateTimeInput(attrs={'type': 'datetime-local'}),
            # color 使用自定义的 ColorRadioSelect 插件
            'color': ColorRadioSelect(attrs={"class": "color-radio"}),
        }

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_start_date(self):
        start_date = self.cleaned_data.get('start_date')
        # 使用 timezone.now() 而不是 datetime.now() 以确保时区一致性
        # 将 timezone.now() 转换为 timezone.now().date() 只比较日期
        # date_now = datetime.date()
        date_now = timezone.now().date()
        if start_date > date_now:
            raise ValidationError('开始日期不能大于当前日期')
        return start_date

    def clean_end_date(self):
        start_date = self.cleaned_data.get('start_date')
        end_date = self.cleaned_data.get('end_date')
        date_now = timezone.now().date()
        if end_date is None:
            return end_date
        exist = self.request.project.project_tasks.exists()
        if exist:
            flag_task = models.Task.objects.filter(
                project=self.request.project).order_by('-id').first()
            if end_date < flag_task.task_date:
                raise ValidationError('项目结束日期不能小于最后任务日期！')
        if end_date < start_date or end_date > date_now:
            raise ValidationError('结束日期不能在创建日期之前或在当前日期之后')
        return end_date

    # def clean_status(self):
    #     end_date = self.cleaned_data.get('end_date')
    #     project_status = self.cleaned_data.get('status')
    #     print(end_date, project_status)
    #     # 反向查询此项目下的task
    #     tasks = self.request.project.project_tasks.all()
    #     if project_status == 'Ongoing':
    #         if end_date:
    #             raise ValidationError('存在结束日期，状态不能是进行中')
    #     if project_status == 'Completed':
    #         if not end_date:
    #             raise ValidationError('没有结束日期!')
    #         # 如果查询集为空（即不包含任何对象），exists() 方法将返回 False；
    #         # 如果查询集中至少有一个对象，它将返回 True。
    #         if not tasks.exists():  # if 是true, not 是 false
    #             raise ValidationError('项目没有Tasks!')
    #     else:
    #         return project_status

    def clean_status(self):
        end_date = self.cleaned_data.get('end_date')
        status = self.cleaned_data.get('status')
        print(end_date, status)
        if end_date and status == 'Ongoing':
            raise ValidationError('存在结束日期，状态不能是进行中!')
        if status == 'Completed':
            if not end_date:
                raise ValidationError('没有结束日期不能完成！')
            tasks = self.request.project.project_tasks.all()
            print(tasks)
            if not tasks.exists():
                raise ValidationError('此项目没有Task，不能完成！')
        return status

    def clean_big_project(self):
        category = self.cleaned_data.get('category')
        big_project = self.cleaned_data.get('big_project')
        if big_project:
            if category not in ['新购实施', '添加设备', '添加模块']:
                raise ValidationError('项目类型不正确')
        return big_project

    def clean_value(self):
        big_project = self.cleaned_data.get('big_project')
        value = self.cleaned_data.get('value')
        if big_project and value == 0:
            raise ValidationError('大项目的金额不正确！')
        return value
